package math;

import org.junit.Test;

public class Ex7 {

    class Solution {
        

        //反转整数 如果反转后整数超过 32 位的有符号整数的范围 [−2^31,  231 − 1] ，就返回 0
        public int reverse(int x) {
            if (x < 10 && x > -10) return x;
            int r, res = 0;
            while (x != 0) {
                r = x % 10;
                x /= 10;
                if (res > 214748364 || res == 214748364 && r > 7) return 0;
                if (res < -214748364 || res == -214748364 && r < -8) return 0;
                res = res * 10 + r;
            }
            return res;
        }
    }
    class SolutionX {
        //反转整数 如果反转后整数超过 32 位的有符号整数的范围 [−2^31,  231 − 1] ，就返回 0
        public int reverse(int x) {
            if (x < 10 && x > -10) return x;
            StringBuilder sb = new StringBuilder();
            boolean flag = x >= 0;
            int n = flag ? x : -x;
            while (n != 0) {
                sb.append(n % 10);
                n /= 10;
            }
            String max = null;
            if (flag) {
                max = (Integer.MAX_VALUE + "").substring(1);
            } else {
                max = (Integer.MIN_VALUE + "").substring(1);
            }

            String cur = sb.toString();

            // Integer.MAX_VALUE
            if (cur.length() < max.length() || cur.compareTo(max) <= 0) return flag ? myParse(cur) : -myParse(cur);
            else return 0;
        }

        public int myParse(String num) {
            int len = num.length();
            int res = 0;
            for (int i = 0; i < len; i++) {
                res += (num.charAt(len - i - 1) - '0') * myPow(10, i);
            }
            return res;
        }

        public int myPow(int x, int n) {
            long res = 1, temp = x; 
            while (n != 0) {
                if ((n & 1) != 0) res *= temp;
                temp *= temp;
                n >>>= 1;
            }
            return (int)res;
        }
    }

    @Test
    public void test() {
        System.out.println(new Solution().reverse(-123));
        // System.out.println(new Solution().myPow(2, 10));

    }
}
